import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JSlider;


public class videoPlayback {
	
	private static VideoPlayer display;
	private static SoundClip sound;
	private static Boolean userChanged = false;
	
	public static void main(String arg[]) throws InterruptedException{
		if(arg.length < 2)
		{
			System.out.println("Please type video and audio file names");
			return;
		}
		display = new VideoPlayer(arg[0]);
		sound = new SoundClip(arg[1]);
		YYFrame frame = new YYFrame("YYVideo", display);

		frame.addMouseListener(new MouseListener(){

			@Override
			public void mouseClicked(MouseEvent arg0) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void mouseEntered(MouseEvent arg0) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void mouseExited(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void mousePressed(MouseEvent arg0) {
				// TODO Auto-generated method stub
				videoPlayback.userChanged = true;
				//System.out.println("Set true");
			}

			@Override
			public void mouseReleased(MouseEvent e) {
				// TODO Auto-generated method stub
				JSlider j=(JSlider)(e.getSource());
				//System.out.println(j.getValue());
				float percent = j.getValue()/(float)(j.getMaximum());
				//System.out.println(percent);
				
				display.setPercentage(percent);
				sound.setPercentage(percent);
				userChanged = false;
				
			}

//			@Override
//			public void stateChanged(ChangeEvent e) {
//				// Jump to another frame
//				JSlider j=(JSlider)(e.getSource());
//				if(!j.getValueIsAdjusting()){
//					System.out.println(j.getValue());
//					float percent = j.getValue()/(float)(j.getMaximum());
//					display.setPercentage(percent);
//					sound.setPercentage(percent);
//				}
//			}
			
		});
		
		
	    Thread t1 = new Thread(display);
	    Thread t2 = new Thread(sound);
	    t1.start();
	    t2.start();
	    
	   // long startTime = System.currentTimeMillis();
	   // long elapsedTime = 0;
	    long videoTime = 0;
	    long soundTime = 0;
	    while (true){
	    	videoTime = display.getCurrentTimeStamp() ;//+1000;
	    	soundTime = sound.getCurrentTimeStamp();
	    	//elapsedTime = System.currentTimeMillis() - startTime;
	    	if (videoTime >= soundTime){
	    		display.pause();
	    	} else {
	    		display.start();
	    	}
	    	
		    if (!userChanged){
		    	frame.updatePlayBar(sound.getPercentage());
		    }
	    	/*if (soundTime >= elapsedTime){
	    		sound.pause();
	    	} else {
	    		sound.start();
	    	}*/
	    	//System.out.println(elapsedTime + ", " + videoTime + ", " + soundTime);
	    	Thread.sleep(1);
	    }
	}
	
}
